# coding:utf-8
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QStackedWidget, QVBoxLayout, QLabel,QPushButton,QHBoxLayout
from src.globle import *
from PyQt5.QtCore import Qt,QPoint, QTimer
from fuc_download.download_files import *

from fuc_desktop.fuc_software.software_related_ui import Ui_software_related

from qfluentwidgets import CardWidget,FluentIcon,Pivot, setTheme, Theme ,isDarkTheme, IconWidget, BodyLabel, CaptionLabel, PushButton

class AppCard(CardWidget):
    """ App card """

    def __init__(self, icon, title, content, action, parent=None):
        super().__init__(parent)
        self.iconWidget = IconWidget(icon)
        self.titleLabel = BodyLabel(title, self)
        self.contentLabel = CaptionLabel(content, self)
        self.openButton = PushButton('点击处理', self)
        self.action = action

        self.hBoxLayout = QHBoxLayout(self)
        self.vBoxLayout = QVBoxLayout()

        self.setFixedHeight(73)
        self.iconWidget.setFixedSize(48, 48)
        self.contentLabel.setTextColor("#606060", "#d2d2d2")
        self.openButton.setFixedWidth(120)

        self.hBoxLayout.setContentsMargins(20, 11, 11, 11)
        self.hBoxLayout.setSpacing(15)
        self.hBoxLayout.addWidget(self.iconWidget)

        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.setSpacing(0)
        self.vBoxLayout.addWidget(self.titleLabel, 0, Qt.AlignVCenter)
        self.vBoxLayout.addWidget(self.contentLabel, 0, Qt.AlignVCenter)
        self.vBoxLayout.setAlignment(Qt.AlignVCenter)
        self.hBoxLayout.addLayout(self.vBoxLayout)

        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addWidget(self.openButton, 0, Qt.AlignRight)
        self.openButton.clicked.connect(self.on_open_button_clicked)

    def on_open_button_clicked(self):
        if callable(self.action):
            print(f"回调")
            self.action(self)
        elif isinstance(self.action, tuple):
            print(f"下载")
            download_file(*self.action)

class CustomWidget(QWidget):
    def __init__(self, cards_data, parent=None):
        super().__init__(parent)
        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout.setSpacing(6)
        self.vBoxLayout.setContentsMargins(30, 60, 30, 30)
        self.vBoxLayout.setAlignment(Qt.AlignTop)

        for card_data in cards_data:
            self.addCard(*card_data)

    def addCard(self, icon, title, content, action):
        card = AppCard(icon, title, content,action, self)
        # card.openButton.clicked.connect(lambda: callback(card))
        self.vBoxLayout.addWidget(card, alignment=Qt.AlignTop)
        
class WXMainWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        self.setWindowTitle("微信问题处理")
        self.layout = QVBoxLayout()

        self.button1 = QPushButton("按钮1")
        self.button2 = QPushButton("按钮2")
        self.button3 = QPushButton("按钮3")

        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.layout.addWidget(self.button3)
        self.setLayout(self.layout)
        self.setGeometry(300, 300, 250, 150)
        print(f"微信问题处理")

class software_related(Ui_software_related, QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.pivot = Pivot(self)
        self.stackedWidget = QStackedWidget(self)
        self.vBoxLayout = QVBoxLayout(self)

        # 定义回调函数
        def handle_open_wechat(card):
            print(f"处理微信的打开或下载 for {card.titleLabel.text()}")
            # main_window = WXMainWindow()
            # main_window.show()
            
        def handle_install_wechat(card):
            os.system("sudo apt update")
            if sys_str == "mips64":
                os.system("sudo apt install -y kylin-activation libkylin-activation wechat zlib1g")
            else:
                os.system("sudo apt install -y wechat-beta")
        def handle_wechat_gpu(card):
            os.system("sudo cp /usr/share/applications/wechat.desktop /usr/share/applications/wechat.desktop")
            os.system("sudo sed -i 's/Exec=wechat %U/Exec=wechat  --disable-gpu  %U/' /usr/share/applications/wechat.desktop")
            os.system("sudo sed -i 's/Exec=wechat %U/Exec=wechat  --disable-gpu  %U/' /home/$this_user/桌面/wechat.desktop")

        def handle_login_wechat(card):
            os.system("sudo echo 'deb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.0 main restricted universe multiverse\ndeb http://archive2.kylinos.cn/DEB/KYLIN_DEB V10-SP1 main all\ndeb http://archive.kylinos.cn/kylin/KYLIN-ALL 10.0-fixs main'> /etc/apt/sources.list")
            os.system("sudo apt update && sudo apt install -y kylin-activation libkylin-activation")

        def handle_kill_wechat():
            os.system("sudo killall -9 weixin || sudo killall -9 wechat")

        def handle_open_qq(card):
            print(f"处理QQ的打开或下载 for {card.titleLabel.text()}")

        def handle_down_sunlogin(card):
            os.system("xhost +")
            print(f"处理向日葵下载 for {card.titleLabel.text()}")
            os.system("sudo apt update && sudo apt install -y sunloginclient")

        def handle_down_todesk(card):
            os.system("xhost +")
            os.system("sudo apt update && sudo apt install -y todesk")
            print(f"执行完了")

        def handle_clean_Kingsoft():
            os.chdir(user_home)
            subprocess.call("quickstartoffice stop", shell=True)
            os.system("rm -rf .config/Kingsoft")
            os.system("rm -rf .local/share/Kingsoft")
            subprocess.call("quickstartoffice start", shell=True)
        
        def handle_cat_Kingsoft():
            wps_content=os.system("tail -c 60 /opt/kingsoft/.auth/license2.dat | head -c 50 | tr -d '\00'")
            
        def handle_down_wpsperson():
            os.system("dpkg -l | grep wps | awk '{print $2}' | xargs sudo dpkg --force-all --purge ")
            download_file('wps_personal','deb')

        def handle_font_shell():
            pass
        
        def handle_change_deb():
            pass
        def fuc_crossover():
            os.chdir(user_home)
            os.chdir(".cxoffice/")
            os.system('find . -name ".eval" -exec rm -f {} \;')
            os.system('sudo rm -f {}')


        # 准备卡片数据和回调函数
        # 1.社交软件
        contact_cards = [
            (":/contact/wechatico", "微信下载", "在公司源中安装微信", handle_install_wechat),
            (":/contact/wechatgpu", "微信禁用gpu", "V10-Mips--微信禁用gpu--适用于微信闪退及卡顿。", handle_wechat_gpu),
            (":/contact/wechatbad", "微信登录失败", "V10-Mips/arm--微信登录提示登录失败error、老Mips激活过期后微信不可用", handle_login_wechat),
            (":/contact/wechatkill", "杀微信进程", "双击微信图标无反应可尝试", handle_kill_wechat),
            (":/contact/wechat2ico", "微信下载2", "手动指定公司源下载微信",  ('wechat-beta', 'deb')),
            (":/contact/qq", "新版QQ下载", "新版QQ下载",  ('tencent_linuxqq', 'deb')),
            (":/contact/closeipv6", "微信QQ二维码不出现", "微信QQ二维码：1.手动找到安全中心网络放行端口，2.点此按钮关IPV6", handle_open_qq),
            (":/contact/tencentmetting", "腾讯会议下载", "腾讯会议下载", ('tencent_metting', 'deb')),
            (":/contact/lanxin", "蓝信下载", "只有arm版蓝信", ('lanxin', 'deb'))
        ]

        # 2.远程软件
        remote_cards = [
            (":/remote/sunlogin", "向日葵下载", "公司源中安装向日葵", lambda: os.system("sudo apt update && sudo apt install -y sunloginclient")),
            (":/remote/todesk", "Todesk下载", "公司源中安装Todesk,此软件无mips", handle_down_todesk),
            (":/remote/todesk2", "Todesk官网下载", "Todesk官网地址安装，此软件无mips", ('todesk', 'deb')),
            (":/remote/sunlogin2", "离线下载-向日葵", "老版本离线安装向日葵10.0版---V10MIPS常用，arm有问题也可用这个", ('sunlogin', 'deb'))
        ]
        # 3.影音下载
        movieMusicDown_cards = [
            (":/movieMusicDown/bilibili", "哔哩哔哩", "bilibili客户端", ('bilibilidl', 'deb')),
            (":/movieMusicDown/YesPlaymusic", "YesPlaymusic", "网易云第三方", ('yesplaymusic', 'deb')),
            (":/movieMusicDown/lxmusic", "落雪音乐", "落雪音乐，需百度搜六音音源等", ('lxmusic', 'deb')),
            (":/movieMusicDown/aliyunpan", "阿里云盘小白羊", "阿里云盘第三方客户端", ('aliyunpan', 'deb'))
        ]
        # 4.编辑软件
        edit_cards = [
            (":/edit/fonts", "字体管理器", "在公司源中安装字体管理器-老版本V10常用", lambda: os.system('sudo apt install -y gnome-font-viewer')),
            (":/edit/fontsshell", "批量安装字体脚本", "点开ttf文件所在文件夹", handle_font_shell),
            (":/edit/wpsclean", "清除wps缓存", "清除wps缓存", handle_clean_Kingsoft),
            (":/edit/wpsserial", "查看wps激活序列号", "查看wps激活序列号", handle_cat_Kingsoft),
            (":/edit/wpspersonal", "安装wps免费个人版", "安装wps免费个人版", handle_down_wpsperson),
            (":/edit/notepad", "安装notepad--", "安装notepad--", ('notepad', 'deb'))
        ]
        # 5.网络浏览器
        netBrowser_cards = [
            (":/netBrowser/flash", "尝试给浏览器装flash插件", "尝试给浏览器装flash插件", lambda: os.system('sudo apt install -y kylin-flash-plugin')),
            (":/netBrowser/360browser", "下载360浏览器", "公司源中下载360浏览器", lambda: os.system('sudo apt install browser360-cn-stable')),
            (":/netBrowser/easyconnect", "easyconnect下载", "老V10-easyconnect下载，新版已换atrust，需找天融信公司要", ('easyconnect', 'deb'))
        ]
        # 6.编程软件
        code_cards = [
            (":/code/unpack", "解包后重新打包", "比如统信的deb，去掉依赖并添加开始菜单图标", handle_change_deb),
            (":/code/vscode", "安装vscode", "最新版地址：https://code.visualstudio.com/Download#，需要特定网络", ('vscode', 'deb')),
            (":/code/qtcreator", "安装qtcreator", "可在商店直接搜索安装", lambda: os.system('sudo apt install qtcreator qtcreator-data')),
            (":/code/git", "安装git", "安装git", lambda: os.system('sudo apt install git')),
            (":/code/cmake", "安装make\cmake", "安装make\cmake", lambda: os.system('sudo apt install make cmake')),
            (":/code/gcc", "安装g++、gcc、cpp", "安装g++、gcc、cpp", lambda: os.system('sudo apt install g++ gcc cpp')),
            (":/code/qt", "安装qt工具和库", "可能有问题", lambda: os.system('sudo apt install qtbase5-dev qt5-qmake qtbase5-dev-tools libqt5printsupport5 libqt5xmlpatterns5-dev'))
        ]

        self.contactInterface = CustomWidget(contact_cards)
        self.remoteInterface = CustomWidget(remote_cards)
        self.movieMusicDownInterface = CustomWidget(movieMusicDown_cards)
        self.editInterface = CustomWidget(edit_cards)
        self.netBrowserInterface = CustomWidget(netBrowser_cards)
        self.codeInterface = CustomWidget(code_cards)

        self.addSubInterface(self.contactInterface, 'contactInterface', '社交软件')
        self.addSubInterface(self.remoteInterface, 'remoteInterface', '远程软件')
        self.addSubInterface(self.movieMusicDownInterface, 'movieMusicDownInterface', '影音下载')
        self.addSubInterface(self.editInterface, 'editInterface', '编辑软件')
        self.addSubInterface(self.netBrowserInterface, 'netBrowserInterface', '网络浏览器')
        self.addSubInterface(self.codeInterface, 'codeInterface', '编程软件')

        self.vBoxLayout.addWidget(self.pivot, 0, Qt.AlignHCenter)
        self.vBoxLayout.addWidget(self.stackedWidget)
        self.vBoxLayout.setContentsMargins(30, 0, 30, 30)

        self.stackedWidget.currentChanged.connect(self.onCurrentIndexChanged)
        self.stackedWidget.setCurrentWidget(self.contactInterface)
        self.pivot.setCurrentItem(self.contactInterface.objectName())

    def addSubInterface(self, widget: QWidget, objectName, text):
        widget.setObjectName(objectName)
        self.stackedWidget.addWidget(widget)
        self.pivot.addItem(
            routeKey=objectName,
            text=text,
            onClick=lambda: self.stackedWidget.setCurrentWidget(widget)
        )

    def onCurrentIndexChanged(self, index):
        widget = self.stackedWidget.widget(index)
        self.pivot.setCurrentItem(widget.objectName())
